package com.fh.controller.building.contract;

import com.fh.controller.base.BaseController;
import com.fh.controller.logAop.MethodLog;
import com.fh.controller.system.tools.GetDatalayui;
import com.fh.controller.system.tools.PushToApp;
import com.fh.controller.system.tools.errorutils;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.attachment.AttachmentService;
import com.fh.service.building.RecordService;
import com.fh.service.building.contract.ContractService;
import com.fh.service.building.contract.LoanService;
import com.fh.service.building.customer.CustomerService;
import com.fh.service.building.message.SysMessageService;
import com.fh.service.hydropower.HydropowerService;
import com.fh.service.role.ShsRoleService;
import com.fh.service.system.user.UserService;
import com.fh.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.jsoup.helper.DataUtil;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 * Created by caozengling on 2017/9/22.
 */
@Controller
@RequestMapping(value = "/contract")
public class ContractController extends BaseController {
    @Resource(name = "contractService")
    private ContractService contractService;

    @Resource(name = "hydropowerService")
    private HydropowerService hydropowerService;

    @Resource(name = "attachmentService")
    private AttachmentService attachmentService;
    @Resource(name = "recordService")
    private RecordService recordService;
    @Resource(name = "sysMessageService")
    private SysMessageService sysMessageService;
    @Resource(name = "shsRoleService")
    private ShsRoleService roleService;
    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "customerService")
    private CustomerService customerService;
    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource(name = "loanService")
    private LoanService loanService;

    /**
     * 返回json
     */
    @RequestMapping(value = "/json")
    @ResponseBody
    public Object json(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        try {
            pd = this.getPageData();
            getPData(page, pd);
            varList = contractService.list(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 新增
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() {
        logBefore(logger, "修改Business");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            contractService.edit(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }



    /**
     * 进行中的合同
     */
    @RequestMapping(value = "/contracting")
    @ResponseBody
    @MethodLog(remark="3213")
    public Object contracting(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        try {
            pd = this.getPageData();
            if(null!=pd.get("TEN_STA")&&StringHelper.isNotEmpty(pd.get("TEN_STA").toString())){
                pd.put("TEN_STA",pd.getString("TEN_STA")+"-01");//承租日期
                pd.put("TEN_END",pd.getString("TEN_END")+"-30");//合同结束日期
            }
            getPData(page, pd);
            varList = contractService.listcontracting(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 已完结的合同
     */
    @RequestMapping(value = "/contractywj")
    @ResponseBody
    public Object contractywj(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        try {
            pd = this.getPageData();
            getPData(page, pd);
            varList = contractService.listcontractywj(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }
    /**
     * 待完结的合同
     */
    @RequestMapping(value = "/contractdwj")
    @ResponseBody
    public Object contractdwj(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        try {
            pd = this.getPageData();
            getPData(page, pd);
            varList = contractService.listcontractdwj(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 审批中的合同
     */
    @RequestMapping(value = "/contractshenpizhong")
    @ResponseBody
    public Object contractshenpizhong(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("CREATE_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = contractService.contractshenpizhong(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 暂存的合同
     */
    @RequestMapping(value = "/contractzancun")
    @ResponseBody
    public Object contractzancun(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("CREATE_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = contractService.contractzancun(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }
    /**
     * 将到期的合同
     */
    @RequestMapping(value = "/contractjdq")
    @ResponseBody
    public Object contractjdq(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("CREATE_ID", user.getUSER_ID());
            if(pd.containsKey("CON_END_DATE")){
                pd.put("CON_END_DATE",pd.get("CON_END_DATE"));
            }else {
                pd.put("CON_END_DATE", DateUtil.getAfterDayDate("90"));
            }
            getPData(page, pd);
            varList = contractService.contractjdq(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 审批事项 待审核的合同
     */
    @RequestMapping(value = "/contractingShenHe")
    @ResponseBody
    public Object contractingShenHe(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd.put("USER_ID", user.getUSER_ID());
            PageData dataAuth = roleService.authListByLoginUser(pd);
            pd = this.getPageData();
            if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                String dataStr = "(";
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_1") != -1) {
                    //一级权限
                    dataStr += "\"01\",\"9\",\"12\",\"5\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_2") != -1) {
                    //二级权限
                    dataStr += "\"02\",\"902\",\"1202\",\"502\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_3") != -1) {
                    //三级权限
                    dataStr += "\"03\",\"903\",\"1203\",\"503\",";
                }
                if (dataAuth.get("AUTH_CODE").toString().indexOf("SHQX_4") != -1) {
                    //四级权限
                    dataStr += "\"04\",\"904\",\"1204\",\"504\",";
                }

                dataStr += "\"-1\")";
                pd.put("CHECK_STATE", dataStr);
            }
            getPData(page, pd);
            varList = contractService.listcontractingShenHe(page);
            //把待审核的合同 添加到 消息中

            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 审批事项 已审核的合同
     */
    @RequestMapping(value = "/contractingYiShenHe")
    @ResponseBody
    public Object contractingYiShenHe(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = contractService.listcontractingYiShenHe(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 合同列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public PageData list() {
        logBefore(logger, "Business列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            List<PageData> list = contractService.listAll(pd);//获取合同基本信息
            PageData con = new PageData();
            PageData data= new PageData();
            int conNum=Integer.parseInt(pd.getString("cod"));//获取第几个合同
            if (list.size() == 1) {
                con.put("id",list.get(0).get("id"));
                List<PageData> propertyData = contractService.findPropertyByContractId(con);//物业基本信息
                List<PageData> initReadData = contractService.findInitRead(con);
                List<PageData> discountData = contractService.findDiscountByContractId(con);//租金递增率
                res.put("discount", discountData);
                res.put("property", propertyData);
                res.put("initRead", initReadData);
                res.put("data", list.get(0));
            }else if (list.size() > 0) {
                con.put("id",list.get(conNum).get("id"));
                List<PageData> propertyData = contractService.findPropertyByContractId(con);//物业基本信息
                List<PageData> initReadData = contractService.findInitRead(con);
                List<PageData> discountData = contractService.findDiscountByContractId(con);//租金递增率
                res.put("discount", discountData);
                res.put("property", propertyData);
                res.put("initRead", initReadData);
                res.put("data", list.get(conNum));
            }else {
                res.put("data", "");
            }
            res.put("ConSum",list.size());//返回合同的数目 前台切换合同计算用
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
    /**
     *  历史合同列表
     */
    @RequestMapping(value = "/HistoryContract")
    @ResponseBody
    public PageData HistoryContract() {
        logBefore(logger, "Business列表");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        try {
            List<PageData> list = contractService.HistoryContract(pd);//获取历史合同基本信息
            PageData con = new PageData();
            PageData data= new PageData();
            if (list.size()>0) {
                res.put("data", list);
            }else {
                res.put("data", "");
            }
            res.put("ConSum",list.size());
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 合同删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public PageData delete() {
        logBefore(logger, "删除合同");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            contractService.delContract(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 新增业务-其他信息
     */
    @RequestMapping(value = "/addOtherInformation")
    @ResponseBody
    public PageData addOtherInformation() {
        logBefore(logger, "新增业务-其他信息");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        
        try {
            contractService.edit(pd);
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     *  正在审批中的合同 取消操作
     */
    @RequestMapping(value = "/cancelShenpi")
    @ResponseBody
    public PageData cancelShenpi() {
        logBefore(logger, "取消审批合同");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            //pd.put("checkState", "1");
            pd.put("STATE", "2d18b637cacf44cc8cb2ead91e496036");
            pd.put("id",pd.get("CONTRACT_ID"));
            String CHECK_STATE=pd.get("CHECK_STATE").toString();
            if ("新建不通过".equals(CHECK_STATE)){
                pd.put("IS_DEL",1);//删除当前的任务
                pd.put("checkState",2);
                contractService.cancelShenpi(pd);
            }
            if ("退租待审核".equals(CHECK_STATE)){
                pd.put("checkState",1);
                contractService.cancelShenpi(pd);
            }
            if ("退租不通过".equals(CHECK_STATE)){
                pd.put("checkState",1);
                contractService.cancelShenpi(pd);
            }
            if ("作废待审核".equals(CHECK_STATE)){
                pd.put("checkState",1);
                contractService.cancelShenpi(pd);
            }
            if ("作废审核不通过".equals(CHECK_STATE)){
                pd.put("checkState",1);
                contractService.cancelShenpi(pd);
            }
            if ("变更待审核".equals(CHECK_STATE)){
                //fixme 变更待审核的当前操作对象
                pd.put("checkState",1);
                pd.put("IS_DEL",1);//删除当前的任务
                contractService.cancelShenpi(pd);
            }
            if ("变更审核不通过".equals(CHECK_STATE)){
                pd.put("checkState",13);
                pd.put("IS_DEL",1);//删除当前的任务
                contractService.cancelShenpi(pd);
            }
            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /****************************** lr合同 ****************************************/

    /**
     * 新增--保存合同
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() {

        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);
        logBefore(logger, "保存合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String contractId = this.get32UUID();

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray ROOMS = (JSONArray) map2.get("ROOMS");
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");
            JSONArray BONDS = (JSONArray) map2.get("BONDS");
            JSONArray DISCOUNT = (JSONArray) map2.get("DISCOUNT");
            JSONArray PROPERTY = (JSONArray) map2.get("PROPERTY");
            JSONArray BILL = (JSONArray) map2.get("BILL");
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");

            String tenantId = this.get32UUID();
            // 保存租户信息
            if (TENANT != null && !TENANT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", tenantId);    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                pd.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                pd.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                pd.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                pd.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                pd.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                pd.put("BYNAME", TENANT.get("BYNAME"));
                contractService.saveTenant(pd);
            }
            // 保存合同信息
            if (CONTRACT != null && !CONTRACT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", contractId);    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                pd.put("UPDATE_DATE", new DateUtil().getTime());
                pd.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                pd.put("PERSON_ID", tenantId);
                pd.put("CREATE_TIME", new DateUtil().getTime());
                pd.put("CONTRACT_NUM", CONTRACT.get("CONTRACT_NUM"));
                pd.put("LEASE", CONTRACT.get("LEASE"));
                pd.put("RENT", CONTRACT.get("UNIT_RENT_MONEY"));
                pd.put("UNIT", CONTRACT.get("UNIT"));
                pd.put("PAY_DAY_MONTH", CONTRACT.get("PAY_DAY_MONTH"));
                pd.put("INCREAS_TYPE", CONTRACT.get("INCREAS_TYPE"));
                pd.put("AREA", CONTRACT.get("AREA"));
                pd.put("INFO", CONTRACT.get("INFO"));
                pd.put("BOND", CONTRACT.get("DEPOSIT_MONEY"));
                pd.put("LATE_FEE", CONTRACT.get("LATE_FEE"));
                pd.put("PAYMENT_PERIOD", CONTRACT.get("PAYMENT_PERIOD"));
                pd.put("PAY_TYPE", CONTRACT.get("PAY_TYPE"));
                pd.put("ANT_PAY_DAY", CONTRACT.get("ANT_PAY_DAY"));
                pd.put("PAY_TX_DAYS", CONTRACT.get("PAY_TX_DAYS"));
                pd.put("END_TX_DAYS", CONTRACT.get("END_TX_DAYS"));
                pd.put("LATE_FEE_DAYS", CONTRACT.get("LATE_FEE_DAYS"));
                pd.put("CON_DATE", CONTRACT.get("CON_DATE"));
                pd.put("CON_HR_DATE", CONTRACT.get("CON_HR_DATE"));
                pd.put("CON_TEN_DATE", CONTRACT.get("CON_TEN_DATE"));
                pd.put("CON_END_DATE", CONTRACT.get("CON_END_DATE"));
                pd.put("CON_OUTF_DATE", CONTRACT.get("CON_OUTF_DATE"));
                pd.put("CON_OUTL_DATE", CONTRACT.get("CON_OUTL_DATE"));
                pd.put("FKFP_TYPE", CONTRACT.get("FKFP_TYPE"));
                pd.put("FKFP_MONEY", CONTRACT.get("FKFP_MONEY"));
                pd.put("WARN_TO_DATE", "");
                pd.put("ROOM_ID", "");
                pd.put("TRNANTRY", "");
                pd.put("PAY_BET", "");
                pd.put("PAY_PAY", "");
                pd.put("CONTRACT_ATT", "");
                pd.put("RENT_DETAILS_ID", "");
                pd.put("RECORD_ID", "");
                pd.put("CUSTOMER_ID", tenantId);
                pd.put("SIGNER", CONTRACT.get("SIGNER"));
                pd.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                pd.put("CHECK_STATE", CONTRACT.get("CHECK_STATE"));
                pd.put("STATE", CONTRACT.get("STATE"));
                pd.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                pd.put("PROPERTY_BILL_HTML", CONTRACT.get("PROPERTY_BILL_HTML"));
                pd.put("IF_COLLECTION", CONTRACT.get("IF_COLLECTION"));
                contractService.saveContract(pd);
            }
//            保存押金信息
            if (BONDS.size() > 0) {
                for (int i = 0; i < BONDS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BONDS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("BOND_NAME", jo.get("BOND_NAME"));
                    pd.put("BOND_MONEY", jo.get("BOND_MONEY"));
                    pd.put("SORT", i + 1);
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    contractService.saveBonds(pd);
                }
            }
//            保存附件信息
            if (ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", contractId);
                    pd.put("NAME", jo.get("name"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "contract");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    attachmentService.saveAttachment(pd);
                }
            }
//            保存房间信息
            if (ROOMS.size() > 0) {
                for (int i = 0; i < ROOMS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ROOMS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("ROOM_ID", jo.get("ROOM_ID"));
                    pd.put("WATER_ID", jo.get("WATER_ID"));
                    pd.put("ELEC_ID", jo.get("ELEC_ID"));
                    pd.put("ROOM_AREA", jo.get("ROOM_AREA"));
                    contractService.saveRooms(pd);

//                    将所有关联水电表的状态更改为新合同
//                    hydropowerService.updateIsNew(pd);

                }
            }
//            保存联系人信息
            if (CONTACTS.size() > 0) {
                for (int i = 0; i < CONTACTS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) CONTACTS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("CONTACTS_NAME", jo.get("CONTACTS_NAME"));
                    pd.put("CONTACTS_TEL", jo.get("CONTACTS_TEL"));
                    contractService.saveContacts(pd);
                }
            }
//            保存折扣信息
            if (DISCOUNT.size() > 0) {
                for (int i = 0; i < DISCOUNT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) DISCOUNT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("FIRST_YEAR", jo.get("FIRST_YEAR"));
                    pd.put("RENT_PRICR", jo.get("RENT_PRICR"));
                    pd.put("DISCOUNT", jo.get("DISCOUNT"));
                    pd.put("INCREAS_RATE", jo.get("INCREAS_RATE"));
                    pd.put("DISCOUNT_RENT", jo.get("DISCOUNT_RENT"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    contractService.saveDiscount(pd);
                }
            }
//            保存物业合同信息
            if (PROPERTY.size() > 0) {
                for (int i = 0; i < PROPERTY.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) PROPERTY.get(i);
                    String propertyId = this.get32UUID();
                    pd.put("ID", propertyId);    //主键
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("CODE", jo.get("CODE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("CHARGE_DATE_TYPE", jo.get("CHARGE_DATE_TYPE"));
                    pd.put("CHARGE_DATE", jo.get("CHARGE_DATE"));
                    pd.put("CHARGE_TYPE", jo.get("CHARGE_TYPE"));
                    pd.put("CHARGE_PRICE", jo.get("CHARGE_PRICE"));
                    pd.put("LN_UNIT", jo.get("LN_UNIT"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    pd.put("LATE_FEE_DAYS", jo.get("LATE_FEE_DAYS"));
                    pd.put("PAY_TX_DAYS", jo.get("PAY_TX_DAYS"));
                    pd.put("PAY_DAYS", jo.get("PAY_DAYS"));
                    pd.put("DATE_START_MONTH", jo.get("START_MONTH"));
                    pd.put("DATE_START_DAY", jo.get("START_DAY"));
                    pd.put("DATE_END_MONTH", jo.get("END_MONTH"));
                    pd.put("DATE_END_DAY", jo.get("END_DAY"));
                    pd.put("VALUATION_TYPE", 0);
                    pd.put("PEOPLE_BI", 0);
                    pd.put("IS_DEFAULT", jo.get("IS_DEFAULT"));
                    pd.put("DEFAULT_ID", jo.get("DEFAULT_ID"));
                    pd.put("PROPERTY_FPZB", jo.get("PROPERTY_FPZB"));
                    pd.put("PROPERTY_TYPE_ID", jo.get("PROPERTY_TYPE_ID"));
                    pd.put("INFO", jo.get("INFO"));
                    if (jo.get("INIT_READ") != null && !jo.get("INIT_READ").equals("")) {
                        JSONArray initRead = (JSONArray) jo.get("INIT_READ");
                        if (initRead != null && initRead.size() > 0) {
                            for (int j = 0; j < initRead.size(); j++) {
                                PageData tPd = new PageData();
                                JSONObject tJo = (JSONObject) initRead.get(j);
                                tPd.put("ID", this.get32UUID());
                                tPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                tPd.put("HYDROPOWER_ID", tJo.get("HYDROPOWER_ID"));
                                tPd.put("INIT_READ", tJo.get("INIT_READ"));
                                tPd.put("INIT_READ_TIME", tJo.get("INIT_READ_TIME"));
                                contractService.saveInitRead(tPd);

                                tPd.put("IS_DEL", 0); //是否删除
                                tPd.put("SORT", 1); //排序
                                tPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                                tPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                                tPd.put("IS_BILL", 1);
                                tPd.put("IS_NEW", 2);
                                contractService.saveInitReadDetail(tPd);

//                                保存电表比例
                                if (tJo.get("DBBL") != null && !tJo.get("DBBL").equals("")) {
                                    JSONArray dbbl = (JSONArray) tJo.get("DBBL");
                                    for (int k = 0; k < dbbl.size(); k++) {
                                        PageData kPd = new PageData();
                                        JSONObject kJo = (JSONObject) dbbl.get(k);
                                        kPd.put("CONTRACT_ID", contractId);
                                        kPd.put("ROOM_ID", kJo.getString("PROJECTID"));
                                        kPd.put("E_BL", kJo.getString("BL"));
                                        contractService.saveBL(kPd);
                                    }
                                }
//                                保存水表比例
                                if (tJo.get("SBBL") != null && !tJo.get("SBBL").equals("")) {
                                    JSONArray sbbl = (JSONArray) tJo.get("SBBL");
                                    for (int k = 0; k < sbbl.size(); k++) {
                                        PageData kPd = new PageData();
                                        JSONObject kJo = (JSONObject) sbbl.get(k);
                                        kPd.put("CONTRACT_ID", contractId);
                                        kPd.put("ROOM_ID", kJo.getString("PROJECTID"));
                                        kPd.put("W_BL", kJo.getString("BL"));
                                        contractService.saveBL(kPd);
                                    }
                                }
                            }
                        }
                    }
                    /*if (jo.get("TIRERED") != null && !jo.get("TIRERED").equals("")) {
                        JSONArray tirered = (JSONArray) jo.get("TIRERED");
                        if (tirered != null && tirered.size() > 0) {
                            for (int j = 0; j < tirered.size(); j++) {
                                PageData tPd = new PageData();
                                JSONObject tJo = (JSONObject) tirered.get(j);
                                tPd.put("ID", this.get32UUID());
                                tPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                tPd.put("START_READ", tJo.get("START_READ"));
                                tPd.put("END_READ", tJo.get("END_READ"));
                                tPd.put("PRICE", tJo.get("PRICE"));
                                contractService.saveTirered(tPd);
                            }
                        }
                    }
                    if (jo.get("ANTH_PROPORTION") != null && !jo.get("ANTH_PROPORTION").equals("")) {
                        JSONArray anthProportion = (JSONArray) jo.get("ANTH_PROPORTION");
                        if (anthProportion != null && anthProportion.size() > 0) {
                            for (int j = 0; j < anthProportion.size(); j++) {
                                PageData aPd = new PageData();
                                JSONObject aJo = (JSONObject) anthProportion.get(j);
                                aPd.put("ID", this.get32UUID());
                                aPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                aPd.put("ROOM_ID", aJo.get("ROOM_ID"));
                                aPd.put("PROPORTION", aJo.get("PROPORTION"));
                                contractService.saveAnthProportion(aPd);
                            }
                        }
                    }*/
                    contractService.saveProperty(pd);
                }
            }
//            保存账单信息
            if (BILL.size() > 0) {
                for (int i = 0; i < BILL.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BILL.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("IS_DEL", 0); //是否删除
                    pd.put("SORT", jo.get("SORT")); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建人ID
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("TENANT_ID", tenantId);
                    pd.put("START_DATE", jo.get("START_DATE"));
                    pd.put("END_DATE", jo.get("END_DATE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("TOTAL_PRICE", jo.get("TOTAL_PRICE"));
                    pd.put("BILL_TYPE", jo.get("BILL_TYPE"));
                    pd.put("BILL_NAME", jo.get("BILL_NAME"));
                    pd.put("STATE", jo.get("STATE"));
                    pd.put("ACT_PAY_DATE", jo.get("ACT_PAY_DATE"));
                    pd.put("INFO", jo.get("INFO"));
                    pd.put("PROPERTY_ID", jo.get("PROPERTY_ID"));
                    pd.put("PAY_TYPE", "");
                    pd.put("PAY_TYPE_PROPORTION", "");
                    pd.put("PAY_TYPE_MONEY", "");
                    pd.put("MAKE_BILL_TYPE", jo.get("MAKE_BILL_TYPE"));
                    pd.put("ALLOT_BILL", jo.get("ALLOT_BILL"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));

                    contractService.saveBill(pd);
                }
            }
            // 保存代收信息
            if (COLLECTION != null && !COLLECTION.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", this.get32UUID());    //主键
                pd.put("CONTRACT_ID", contractId);    //合同ID
                pd.put("TX_TEL", COLLECTION.get("TX_TEL"));
                pd.put("TX_EMAIL", COLLECTION.get("TX_EMAIL"));
                pd.put("BANK_CODE", COLLECTION.get("BANK_CODE"));
                pd.put("ACCOUNT_TYPE", COLLECTION.get("ACCOUNT_TYPE"));
                pd.put("ACCOUNT_NO", COLLECTION.get("ACCOUNT_NO"));
                pd.put("ACCOUNT_NAME", COLLECTION.get("ACCOUNT_NAME"));
                pd.put("PROVINCE", COLLECTION.get("PROVINCE"));
                pd.put("CITY", COLLECTION.get("CITY"));
                pd.put("BANK_NAME", COLLECTION.get("BANK_NAME"));
                pd.put("ACCOUNT_PROP", COLLECTION.get("ACCOUNT_PROP"));
                pd.put("CURRENCY", COLLECTION.get("CURRENCY"));
                pd.put("ID_TYPE", COLLECTION.get("ID_TYPE"));
                pd.put("ID_CARD", COLLECTION.get("ID"));
                pd.put("TEL", COLLECTION.get("TEL"));
                pd.put("ABSTRACT", COLLECTION.get("ABSTRACT"));
                contractService.saveCollection(pd);
            }
//            保存提醒信息
            if (REMINDS.size() > 0) {
                for (int i = 0; i < REMINDS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) REMINDS.get(i);
//                    pd.put("MESSAGE_ID", this.get32UUID());    //主键
//                    pd.put("IS_DELETED", 0); //是否删除
                    pd.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
//                    pd.put("CREATE_TIME", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("BILL_ID", "");
                    pd.put("TITLE", jo.get("TYPE") + "收取提醒!");
                    pd.put("CONTENT", jo.get("TYPE") + "收取提醒!");
                    pd.put("TYPE", 3);
//                    pd.put("IS_READ", 0);
                    pd.put("RECEIVER_USERID", "");
                    pd.put("REMIND_TIME", jo.get("PAY_DATE"));

                    sysMessageService.saveMessage(pd);
                }
            }

            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "创建合同，提交审核");//提交合同
            oppd.put("CONTRACT_ID", contractId);
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);

            //--------------------个推消息---------------------
            //个推消息
            PageData CID = new PageData();
            String title = "你有一条待审批的合同2";
            String text = "请前去审批";
            List<PageData> listcid = contractService.findlistCID(CID);
            List<String> cid= PushToApp.userCID("SPQX_HTSP",listcid);//获取由此权限的用户cid
            if(cid.size()>0){
                JSONObject json =new JSONObject();
                json.put("ID",contractId);
                json.put("TYPE",0);
                json.put("TITLE","你有一条待审批的合同");
                json.put("TEXT","请前去审批");
                String ID = json.toString();
//                PushToApp.PushPrivate(title,text,cid,ID);
            }
            //--------------------个推消息---------------------


            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            logger.error(e.toString(), e);
            PageData pd = new PageData();
            pd.put("id", contractId);
            try {
                contractService.delContract(pd);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 新增--暂存合同
     */
    @RequestMapping(value = "/temporaryStorage")
    @ResponseBody
    public PageData zancun() {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

        logBefore(logger, "暂存合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String contractId = this.get32UUID();

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray ROOMS = (JSONArray) map2.get("ROOMS");
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");
            JSONArray BONDS = (JSONArray) map2.get("BONDS");
            JSONArray DISCOUNT = (JSONArray) map2.get("DISCOUNT");
            JSONArray PROPERTY = (JSONArray) map2.get("PROPERTY");
            JSONArray BILL = (JSONArray) map2.get("BILL");
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");

            String tenantId = this.get32UUID();
            // 保存租户信息
            if (TENANT != null && !TENANT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", tenantId);    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                pd.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                pd.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                pd.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                pd.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                pd.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                pd.put("BYNAME", TENANT.get("BYNAME"));
                contractService.saveTenant(pd);
            }
            // 保存合同信息
            if (CONTRACT != null && !CONTRACT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", contractId);    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                pd.put("PERSON_ID", tenantId);
                pd.put("CREATE_TIME", new DateUtil().getTime());
                pd.put("CONTRACT_NUM", CONTRACT.get("CONTRACT_NUM"));
                pd.put("LEASE", CONTRACT.get("LEASE"));
                pd.put("RENT", CONTRACT.get("UNIT_RENT_MONEY"));
                pd.put("UNIT", CONTRACT.get("UNIT"));
                pd.put("PAY_DAY_MONTH", CONTRACT.get("PAY_DAY_MONTH"));
                pd.put("INCREAS_TYPE", CONTRACT.get("INCREAS_TYPE"));
                pd.put("AREA", CONTRACT.get("AREA"));
                pd.put("INFO", CONTRACT.get("INFO"));
                pd.put("BOND", CONTRACT.get("DEPOSIT_MONEY"));
                pd.put("LATE_FEE", CONTRACT.get("LATE_FEE"));
                pd.put("PAYMENT_PERIOD", CONTRACT.get("PAYMENT_PERIOD"));
                pd.put("PAY_TYPE", CONTRACT.get("PAY_TYPE"));
                pd.put("ANT_PAY_DAY", CONTRACT.get("ANT_PAY_DAY"));
                pd.put("PAY_TX_DAYS", CONTRACT.get("PAY_TX_DAYS"));
                pd.put("END_TX_DAYS", CONTRACT.get("END_TX_DAYS"));
                pd.put("LATE_FEE_DAYS", CONTRACT.get("LATE_FEE_DAYS"));
                pd.put("CON_DATE", CONTRACT.get("CON_DATE"));
                pd.put("CON_HR_DATE", CONTRACT.get("CON_HR_DATE"));
                pd.put("CON_TEN_DATE", CONTRACT.get("CON_TEN_DATE"));
                pd.put("CON_END_DATE", CONTRACT.get("CON_END_DATE"));
                pd.put("CON_OUTF_DATE", CONTRACT.get("CON_OUTF_DATE"));
                pd.put("CON_OUTL_DATE", CONTRACT.get("CON_OUTL_DATE"));
                pd.put("FKFP_TYPE", CONTRACT.get("FKFP_TYPE"));
                pd.put("FKFP_MONEY", CONTRACT.get("FKFP_MONEY"));
                pd.put("WARN_TO_DATE", "");
                pd.put("ROOM_ID", "");
                pd.put("TRNANTRY", "");
                pd.put("PAY_BET", "");
                pd.put("PAY_PAY", "");
                pd.put("CONTRACT_ATT", "");
                pd.put("RENT_DETAILS_ID", "");
                pd.put("RECORD_ID", "");
                pd.put("CUSTOMER_ID", tenantId);
                pd.put("SIGNER", CONTRACT.get("SIGNER"));
                pd.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                pd.put("CHECK_STATE", CONTRACT.get("CHECK_STATE"));
                pd.put("STATE", CONTRACT.get("STATE"));
                pd.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                pd.put("PROPERTY_BILL_HTML", CONTRACT.get("PROPERTY_BILL_HTML"));
                pd.put("IF_COLLECTION", CONTRACT.get("IF_COLLECTION"));
                contractService.saveContract(pd);
            }
//            保存押金信息
            if (BONDS.size() > 0) {
                for (int i = 0; i < BONDS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BONDS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("BOND_NAME", jo.get("BOND_NAME"));
                    pd.put("BOND_MONEY", jo.get("BOND_MONEY"));
                    pd.put("SORT", i + 1);
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    contractService.saveBonds(pd);
                }
            }
//            保存附件信息
            if (ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", contractId);
                    pd.put("NAME", jo.get("name"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "contract");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    attachmentService.saveAttachment(pd);
                }
            }
//            保存房间信息
            if (ROOMS.size() > 0) {
                for (int i = 0; i < ROOMS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ROOMS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("ROOM_ID", jo.get("ROOM_ID"));
                    pd.put("WATER_ID", jo.get("WATER_ID"));
                    pd.put("ELEC_ID", jo.get("ELEC_ID"));
                    pd.put("ROOM_AREA", jo.get("ROOM_AREA"));
                    contractService.saveRooms(pd);

//                    将所有关联水电表的状态更改为新合同
//                    hydropowerService.updateIsNew(pd);

                }
            }
//            保存联系人信息
            if (CONTACTS.size() > 0) {
                for (int i = 0; i < CONTACTS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) CONTACTS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("CONTACTS_NAME", jo.get("CONTACTS_NAME"));
                    pd.put("CONTACTS_TEL", jo.get("CONTACTS_TEL"));
                    contractService.saveContacts(pd);
                }
            }
//            保存折扣信息
            if (DISCOUNT.size() > 0) {
                for (int i = 0; i < DISCOUNT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) DISCOUNT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("FIRST_YEAR", jo.get("FIRST_YEAR"));
                    pd.put("RENT_PRICR", jo.get("RENT_PRICR"));
                    pd.put("DISCOUNT", jo.get("DISCOUNT"));
                    pd.put("INCREAS_RATE", jo.get("INCREAS_RATE"));
                    pd.put("DISCOUNT_RENT", jo.get("DISCOUNT_RENT"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    contractService.saveDiscount(pd);
                }
            }
//            保存物业合同信息
            if (PROPERTY.size() > 0) {
                for (int i = 0; i < PROPERTY.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) PROPERTY.get(i);
                    String propertyId = this.get32UUID();
                    pd.put("ID", propertyId);    //主键
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("CODE", jo.get("CODE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("CHARGE_DATE_TYPE", jo.get("CHARGE_DATE_TYPE"));
                    pd.put("CHARGE_DATE", jo.get("CHARGE_DATE"));
                    pd.put("CHARGE_TYPE", jo.get("CHARGE_TYPE"));
                    pd.put("CHARGE_PRICE", jo.get("CHARGE_PRICE"));
                    pd.put("LN_UNIT", jo.get("LN_UNIT"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    pd.put("LATE_FEE_DAYS", jo.get("LATE_FEE_DAYS"));
                    pd.put("PAY_TX_DAYS", jo.get("PAY_TX_DAYS"));
                    pd.put("PAY_DAYS", jo.get("PAY_DAYS"));
                    pd.put("DATE_START_MONTH", jo.get("START_MONTH"));
                    pd.put("DATE_START_DAY", jo.get("START_DAY"));
                    pd.put("DATE_END_MONTH", jo.get("END_MONTH"));
                    pd.put("DATE_END_DAY", jo.get("END_DAY"));
                    pd.put("VALUATION_TYPE", 0);
                    pd.put("PEOPLE_BI", 0);
                    pd.put("IS_DEFAULT", jo.get("IS_DEFAULT"));
                    pd.put("DEFAULT_ID", jo.get("DEFAULT_ID"));
                    pd.put("PROPERTY_FPZB", jo.get("PROPERTY_FPZB"));
                    pd.put("PROPERTY_TYPE_ID", jo.get("PROPERTY_TYPE_ID"));
                    pd.put("INFO", jo.get("INFO"));
                    if (jo.get("INIT_READ") != null && !jo.get("INIT_READ").equals("")) {
                        JSONArray initRead = (JSONArray) jo.get("INIT_READ");
                        if (initRead != null && initRead.size() > 0) {
                            for (int j = 0; j < initRead.size(); j++) {
                                PageData tPd = new PageData();
                                JSONObject tJo = (JSONObject) initRead.get(j);
                                tPd.put("ID", this.get32UUID());
                                tPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                tPd.put("HYDROPOWER_ID", tJo.get("HYDROPOWER_ID"));
                                tPd.put("INIT_READ", tJo.get("INIT_READ"));
                                tPd.put("INIT_READ_TIME", tJo.get("INIT_READ_TIME"));
                                contractService.saveInitRead(tPd);

                                tPd.put("IS_DEL", 0); //是否删除
                                tPd.put("SORT", 1); //排序
                                tPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                                tPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                                tPd.put("IS_BILL", 1);
                                tPd.put("IS_NEW", 2);
                                contractService.saveInitReadDetail(tPd);

//                                保存电表比例
                                if (tJo.get("DBBL") != null && !tJo.get("DBBL").equals("")) {
                                    JSONArray dbbl = (JSONArray) tJo.get("DBBL");
                                    for (int k = 0; k < dbbl.size(); k++) {
                                        PageData kPd = new PageData();
                                        JSONObject kJo = (JSONObject) dbbl.get(k);
                                        kPd.put("CONTRACT_ID", contractId);
                                        kPd.put("ROOM_ID", kJo.getString("PROJECTID"));
                                        kPd.put("E_BL", kJo.getString("BL"));
                                        contractService.saveBL(kPd);
                                    }
                                }
//                                保存水表比例
                                if (tJo.get("SBBL") != null && !tJo.get("SBBL").equals("")) {
                                    JSONArray sbbl = (JSONArray) tJo.get("SBBL");
                                    for (int k = 0; k < sbbl.size(); k++) {
                                        PageData kPd = new PageData();
                                        JSONObject kJo = (JSONObject) sbbl.get(k);
                                        kPd.put("CONTRACT_ID", contractId);
                                        kPd.put("ROOM_ID", kJo.getString("PROJECTID"));
                                        kPd.put("W_BL", kJo.getString("BL"));
                                        contractService.saveBL(kPd);
                                    }
                                }

                            }
                        }
                    }
                    contractService.saveProperty(pd);
                }
            }
//            保存账单信息
            if (BILL.size() > 0) {
                for (int i = 0; i < BILL.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BILL.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("IS_DEL", 0); //是否删除
                    pd.put("SORT", jo.get("SORT")); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建人ID
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间

                    pd.put("CONTRACT_ID", contractId);
                    pd.put("TENANT_ID", tenantId);
                    pd.put("START_DATE", jo.get("START_DATE"));
                    pd.put("END_DATE", jo.get("END_DATE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("TOTAL_PRICE", jo.get("TOTAL_PRICE"));
                    pd.put("BILL_TYPE", jo.get("BILL_TYPE"));
                    pd.put("BILL_NAME", jo.get("BILL_NAME"));
                    pd.put("STATE", jo.get("STATE"));
                    pd.put("ACT_PAY_DATE", jo.get("ACT_PAY_DATE"));
                    pd.put("INFO", jo.get("INFO"));
                    pd.put("PROPERTY_ID", jo.get("PROPERTY_ID"));
                    pd.put("PAY_TYPE", "");
                    pd.put("PAY_TYPE_PROPORTION", "");
                    pd.put("PAY_TYPE_MONEY", "");
                    pd.put("MAKE_BILL_TYPE", jo.get("MAKE_BILL_TYPE"));
                    pd.put("ALLOT_BILL", jo.get("ALLOT_BILL"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));

                    contractService.saveBill(pd);
                }
            }
            // 保存代收信息
            if (COLLECTION != null && !COLLECTION.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", this.get32UUID());    //主键
                pd.put("CONTRACT_ID", contractId);    //合同ID
                pd.put("TX_TEL", COLLECTION.get("TX_TEL"));
                pd.put("TX_EMAIL", COLLECTION.get("TX_EMAIL"));
                pd.put("BANK_CODE", COLLECTION.get("BANK_CODE"));
                pd.put("ACCOUNT_TYPE", COLLECTION.get("ACCOUNT_TYPE"));
                pd.put("ACCOUNT_NO", COLLECTION.get("ACCOUNT_NO"));
                pd.put("ACCOUNT_NAME", COLLECTION.get("ACCOUNT_NAME"));
                pd.put("PROVINCE", COLLECTION.get("PROVINCE"));
                pd.put("CITY", COLLECTION.get("CITY"));
                pd.put("BANK_NAME", COLLECTION.get("BANK_NAME"));
                pd.put("ACCOUNT_PROP", COLLECTION.get("ACCOUNT_PROP"));
                pd.put("CURRENCY", COLLECTION.get("CURRENCY"));
                pd.put("ID_TYPE", COLLECTION.get("ID_TYPE"));
                pd.put("ID_CARD", COLLECTION.get("ID"));
                pd.put("TEL", COLLECTION.get("TEL"));
                pd.put("ABSTRACT", COLLECTION.get("ABSTRACT"));
                contractService.saveCollection(pd);
            }
//            保存提醒信息
            if (REMINDS.size() > 0) {
                for (int i = 0; i < REMINDS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) REMINDS.get(i);
//                    pd.put("MESSAGE_ID", this.get32UUID());    //主键
//                    pd.put("IS_DELETED", 0); //是否删除
                    pd.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
//                    pd.put("CREATE_TIME", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("BILL_ID", "");
                    pd.put("TITLE", jo.get("TYPE") + "收取提醒!");
                    pd.put("CONTENT", jo.get("TYPE") + "收取提醒!");
                    pd.put("TYPE", 3);
//                    pd.put("IS_READ", 0);
                    pd.put("RECEIVER_USERID", "");
                    pd.put("REMIND_TIME", jo.get("PAY_DATE"));
                    sysMessageService.save(pd);
                }
            }

            res.put("data", contractId);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            logger.error(e.toString(), e);
            PageData pd = new PageData();
            pd.put("id", contractId);
            try {
                contractService.delContract(pd);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 根据合同ID获取合同详情信息
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData contractInfo() {
        logBefore(logger, "根据合同ID获取合同详情信息");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            PageData data = new PageData();
            PageData contractData = contractService.findByIdApp(pd);
            List<PageData> roomData = contractService.findRoomByContractId(pd);
            List<PageData> contactData = contractService.findContactByContractId(pd);
            List<PageData> bondData = contractService.findBondByContractId(pd);
            List<PageData> discountData = contractService.findDiscountByContractId(pd);
            List<PageData> billData = contractService.findBillByContractId(pd);
            List<PageData> propertyBillData = contractService.findPropertyBillByContractId(pd);
            List<PageData> propertyData = contractService.findPropertyByContractId(pd);
            List<PageData> attachmentData = attachmentService.findByOId(pd);
            List<PageData> throwLeaseData = contractService.findThrowLease(pd);
            List<PageData> initReadData = contractService.findInitRead(pd);
            List<PageData> BL = contractService.findBL(pd);
            PageData collectionData = contractService.findCollectionByContractId(pd);

            data.put("contract", contractData);
            data.put("room", roomData);
            data.put("contact", contactData);
            data.put("bond", bondData);
            data.put("discount", discountData);
            data.put("bill", billData);
            data.put("propertyBill", propertyBillData);
            data.put("property", propertyData);
            data.put("attachment", attachmentData);
            data.put("throwLease", throwLeaseData);
            data.put("initRead", initReadData);
            data.put("BL", BL);
            data.put("collectionData", collectionData);
            //新增合同的操作权限OPERA_AUTH
            if(null!=pd.get("userid")){
                pd.put("USER_ID", pd.get("userid"));
                PageData dataAuth = roleService.authListByLoginUser(pd);
                if(null!=dataAuth){
                    if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_HTSP")!=-1) {
                        data.put("OPERA_AUTH",1);
                    }else {
                        data.put("OPERA_AUTH",0);
                    }
                }else {
                    data.put("OPERA_AUTH",0);
                }
            }
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 变更合同
     */
    @RequestMapping(value = "/change")
    @ResponseBody
    public PageData change() {

        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);
        logBefore(logger, "变更合同");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String contractId = this.get32UUID();

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONArray ROOMS = (JSONArray) map2.get("ROOMS");
            JSONArray CONTACTS = (JSONArray) map2.get("CONTACTS");
            JSONObject TENANT = (JSONObject) map2.get("TENANT");
            JSONObject CONTRACT = (JSONObject) map2.get("CONTRACT");
            JSONArray BONDS = (JSONArray) map2.get("BONDS");
            JSONArray DISCOUNT = (JSONArray) map2.get("DISCOUNT");
            JSONArray PROPERTY = (JSONArray) map2.get("PROPERTY");
            JSONArray BILL = (JSONArray) map2.get("BILL");
            JSONArray REMINDS = (JSONArray) map2.get("REMINDS");
            JSONArray ATTACHMENT = (JSONArray) map2.get("ATTACHMENT");
            JSONObject COLLECTION = (JSONObject) map2.get("COLLECTION");

            String tenantId = this.get32UUID();
            // 保存租户信息
            if (TENANT != null && !TENANT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", tenantId);    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("INDUSTRY_ID", TENANT.get("INDUSTRY_ID"));
                pd.put("COMPANY_NAME", TENANT.get("COMPANY_NAME"));
                pd.put("BUSINESS_LICENSE", TENANT.get("BUSINESS_LICENSE"));
                pd.put("LEGAL_PERSON_NAME", TENANT.get("LEGAL_PERSON_NAME"));
                pd.put("LEGAL_PERSON_TEL", TENANT.get("LEGAL_PERSON_TEL"));
                pd.put("CONTRACT_ADDRESS", TENANT.get("CONTRACT_ADDRESS"));
                pd.put("BYNAME", TENANT.get("BYNAME"));
                contractService.saveTenant(pd);
            }
            // 保存合同信息
            if (CONTRACT != null && !CONTRACT.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", contractId);    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("UPDATE_DATE", new DateUtil().getTime());//
                pd.put("UPDATE_ID", user.getUSER_ID()); //
                pd.put("SUBMIT_PERSON_ID", user.getUSER_ID());
                pd.put("PERSON_ID", tenantId);
                pd.put("CREATE_TIME", new DateUtil().getTime());
                pd.put("CONTRACT_NUM", CONTRACT.get("CONTRACT_NUM"));
                pd.put("LEASE", CONTRACT.get("LEASE"));
                pd.put("RENT", CONTRACT.get("UNIT_RENT_MONEY"));
                pd.put("UNIT", CONTRACT.get("UNIT"));
                pd.put("PAY_DAY_MONTH", CONTRACT.get("PAY_DAY_MONTH"));
                pd.put("INCREAS_TYPE", CONTRACT.get("INCREAS_TYPE"));
                pd.put("AREA", CONTRACT.get("AREA"));
                pd.put("INFO", CONTRACT.get("INFO"));
                pd.put("BOND", CONTRACT.get("DEPOSIT_MONEY"));
                pd.put("LATE_FEE", CONTRACT.get("LATE_FEE"));
                pd.put("PAYMENT_PERIOD", CONTRACT.get("PAYMENT_PERIOD"));
                pd.put("PAY_TYPE", CONTRACT.get("PAY_TYPE"));
                pd.put("ANT_PAY_DAY", CONTRACT.get("ANT_PAY_DAY"));
                pd.put("PAY_TX_DAYS", CONTRACT.get("PAY_TX_DAYS"));
                pd.put("END_TX_DAYS", CONTRACT.get("END_TX_DAYS"));
                pd.put("LATE_FEE_DAYS", CONTRACT.get("LATE_FEE_DAYS"));
                pd.put("CON_DATE", CONTRACT.get("CON_DATE"));
                pd.put("CON_HR_DATE", CONTRACT.get("CON_HR_DATE"));
                pd.put("CON_TEN_DATE", CONTRACT.get("CON_TEN_DATE"));
                pd.put("CON_END_DATE", CONTRACT.get("CON_END_DATE"));
                pd.put("CON_OUTF_DATE", CONTRACT.get("CON_OUTF_DATE"));
                pd.put("CON_OUTL_DATE", CONTRACT.get("CON_OUTL_DATE"));
                pd.put("FKFP_TYPE", CONTRACT.get("FKFP_TYPE"));
                pd.put("FKFP_MONEY", CONTRACT.get("FKFP_MONEY"));
                pd.put("WARN_TO_DATE", "");
                pd.put("ROOM_ID", "");
                pd.put("TRNANTRY", "");
                pd.put("PAY_BET", "");
                pd.put("PAY_PAY", "");
                pd.put("CONTRACT_ATT", "");
                pd.put("RENT_DETAILS_ID", "");
                pd.put("RECORD_ID", "");
                pd.put("CUSTOMER_ID", tenantId);
                pd.put("SIGNER", CONTRACT.get("SIGNER"));
                pd.put("SIGNER_TEL", CONTRACT.get("SIGNER_TEL"));
                pd.put("CHECK_STATE", "12");
                pd.put("STATE", CONTRACT.get("STATE"));
                pd.put("BILL_HTML", CONTRACT.get("BILL_HTML"));
                pd.put("PROPERTY_BILL_HTML", CONTRACT.get("PROPERTY_BILL_HTML"));
                pd.put("BEFORE_CHANGE_CONTRACT_ID", CONTRACT.get("CONTRACT_ID"));
                /*//把原来的合同的状态 修改为 变更待审核
                PageData pdold = new PageData();
                pdold.put("checkState",12);
                pdold.put("id",CONTRACT.get("CONTRACT_ID"));
                pdold.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
                contractService.check(pdold);*/
                pd.put("DEL_BILL_IDS", CONTRACT.get("BILL_ID"));
                pd.put("IF_COLLECTION", CONTRACT.get("IF_COLLECTION"));
                contractService.saveContract(pd);
            }
//            保存押金信息
            if (BONDS.size() > 0) {
                for (int i = 0; i < BONDS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BONDS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("BOND_NAME", jo.get("BOND_NAME"));
                    pd.put("BOND_MONEY", jo.get("BOND_MONEY"));
                    pd.put("SORT", i + 1);
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    contractService.saveBonds(pd);
                }
            }
//            保存附件信息
            if (ATTACHMENT.size() > 0) {
                for (int i = 0; i < ATTACHMENT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ATTACHMENT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("OID", contractId);
                    pd.put("NAME", jo.get("name"));
                    pd.put("SIZE", jo.get("size"));
                    pd.put("EXT", jo.get("ext"));
                    pd.put("PATH", jo.get("url"));
                    pd.put("TYPE", "contract");
                    pd.put("SORT", i + 1);
                    pd.put("REMARK", "");
                    pd.put("CREATE_TIME", new DateUtil().getTime());
                    pd.put("CREATE_ID", user.getUSER_ID());
                    pd.put("IS_DELETED", 0);
                    attachmentService.saveAttachment(pd);
                }
            }
//            保存房间信息
            if (ROOMS.size() > 0) {
                for (int i = 0; i < ROOMS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) ROOMS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("ROOM_ID", jo.get("ROOM_ID"));
                    pd.put("WATER_ID", jo.get("WATER_ID"));
                    pd.put("ELEC_ID", jo.get("ELEC_ID"));
                    pd.put("ROOM_AREA", jo.get("ROOM_AREA"));
                    contractService.saveRooms(pd);

//                    将所有关联水电表的状态更改为新合同
//                    hydropowerService.updateIsNew(pd);

                }
            }
//            保存联系人信息
            if (CONTACTS.size() > 0) {
                for (int i = 0; i < CONTACTS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) CONTACTS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("CONTACTS_NAME", jo.get("CONTACTS_NAME"));
                    pd.put("CONTACTS_TEL", jo.get("CONTACTS_TEL"));
                    contractService.saveContacts(pd);
                }
            }
//            保存折扣信息
            if (DISCOUNT.size() > 0) {
                for (int i = 0; i < DISCOUNT.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) DISCOUNT.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("FIRST_YEAR", jo.get("FIRST_YEAR"));
                    pd.put("RENT_PRICR", jo.get("RENT_PRICR"));
                    pd.put("DISCOUNT", jo.get("DISCOUNT"));
                    pd.put("INCREAS_RATE", jo.get("INCREAS_RATE"));
                    pd.put("DISCOUNT_RENT", jo.get("DISCOUNT_RENT"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    contractService.saveDiscount(pd);
                }
            }
//            保存物业合同信息
            if (PROPERTY.size() > 0) {
                for (int i = 0; i < PROPERTY.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) PROPERTY.get(i);
                    String propertyId = this.get32UUID();
                    pd.put("ID", propertyId);    //主键
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("CODE", jo.get("CODE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("CHARGE_DATE_TYPE", jo.get("CHARGE_DATE_TYPE"));
                    pd.put("CHARGE_DATE", jo.get("CHARGE_DATE"));
                    pd.put("CHARGE_TYPE", jo.get("CHARGE_TYPE"));
                    pd.put("CHARGE_PRICE", jo.get("CHARGE_PRICE"));
                    pd.put("LN_UNIT", jo.get("LN_UNIT"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    pd.put("LATE_FEE_DAYS", jo.get("LATE_FEE_DAYS"));
                    pd.put("PAY_TX_DAYS", jo.get("PAY_TX_DAYS"));
                    pd.put("PAY_DAYS", jo.get("PAY_DAYS"));
                    pd.put("DATE_START_MONTH", jo.get("START_MONTH"));
                    pd.put("DATE_START_DAY", jo.get("START_DAY"));
                    pd.put("DATE_END_MONTH", jo.get("END_MONTH"));
                    pd.put("DATE_END_DAY", jo.get("END_DAY"));
                    pd.put("VALUATION_TYPE", 0);
                    pd.put("PEOPLE_BI", 0);
                    pd.put("IS_DEFAULT", jo.get("IS_DEFAULT"));
                    pd.put("DEFAULT_ID", jo.get("DEFAULT_ID"));
                    pd.put("PROPERTY_FPZB", jo.get("PROPERTY_FPZB"));
                    pd.put("PROPERTY_TYPE_ID", jo.get("PROPERTY_TYPE_ID"));
                    pd.put("INFO", jo.get("INFO"));
                    if (jo.get("INIT_READ") != null && !jo.get("INIT_READ").equals("")) {
                        JSONArray initRead = (JSONArray) jo.get("INIT_READ");
                        if (initRead != null && initRead.size() > 0) {
                            for (int j = 0; j < initRead.size(); j++) {
                                PageData tPd = new PageData();
                                JSONObject tJo = (JSONObject) initRead.get(j);
                                tPd.put("ID", this.get32UUID());
                                tPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                tPd.put("HYDROPOWER_ID", tJo.get("HYDROPOWER_ID"));
                                tPd.put("INIT_READ", tJo.get("INIT_READ"));
                                tPd.put("INIT_READ_TIME", tJo.get("INIT_READ_TIME"));
                                contractService.saveInitRead(tPd);

                                tPd.put("IS_DEL", 0); //是否删除
                                tPd.put("SORT", 1); //排序
                                tPd.put("CREATE_ID", user.getUSER_ID()); //创建人
                                tPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                                tPd.put("IS_BILL", 1);
                                tPd.put("IS_NEW", 2);
                                contractService.saveInitReadDetail(tPd);

//                                保存电表比例
                                if (tJo.get("DBBL") != null && !tJo.get("DBBL").equals("")) {
                                    JSONArray dbbl = (JSONArray) tJo.get("DBBL");
                                    for (int k = 0; k < dbbl.size(); k++) {
                                        PageData kPd = new PageData();
                                        JSONObject kJo = (JSONObject) dbbl.get(k);
                                        kPd.put("CONTRACT_ID", contractId);
                                        kPd.put("ROOM_ID", kJo.getString("PROJECTID"));
                                        kPd.put("E_BL", kJo.getString("BL"));
                                        contractService.saveBL(kPd);
                                    }
                                }
//                                保存水表比例
                                if (tJo.get("SBBL") != null && !tJo.get("SBBL").equals("")) {
                                    JSONArray sbbl = (JSONArray) tJo.get("SBBL");
                                    for (int k = 0; k < sbbl.size(); k++) {
                                        PageData kPd = new PageData();
                                        JSONObject kJo = (JSONObject) sbbl.get(k);
                                        kPd.put("CONTRACT_ID", contractId);
                                        kPd.put("ROOM_ID", kJo.getString("PROJECTID"));
                                        kPd.put("W_BL", kJo.getString("BL"));
                                        contractService.saveBL(kPd);
                                    }
                                }
                            }
                        }
                    }
                    /*if (jo.get("TIRERED") != null && !jo.get("TIRERED").equals("")) {
                        JSONArray tirered = (JSONArray) jo.get("TIRERED");
                        if (tirered != null && tirered.size() > 0) {
                            for (int j = 0; j < tirered.size(); j++) {
                                PageData tPd = new PageData();
                                JSONObject tJo = (JSONObject) tirered.get(j);
                                tPd.put("ID", this.get32UUID());
                                tPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                tPd.put("START_READ", tJo.get("START_READ"));
                                tPd.put("END_READ", tJo.get("END_READ"));
                                tPd.put("PRICE", tJo.get("PRICE"));
                                contractService.saveTirered(tPd);
                            }
                        }
                    }
                    if (jo.get("ANTH_PROPORTION") != null && !jo.get("ANTH_PROPORTION").equals("")) {
                        JSONArray anthProportion = (JSONArray) jo.get("ANTH_PROPORTION");
                        if (anthProportion != null && anthProportion.size() > 0) {
                            for (int j = 0; j < anthProportion.size(); j++) {
                                PageData aPd = new PageData();
                                JSONObject aJo = (JSONObject) anthProportion.get(j);
                                aPd.put("ID", this.get32UUID());
                                aPd.put("CONTRACT_PROPERTY_ID", propertyId);
                                aPd.put("ROOM_ID", aJo.get("ROOM_ID"));
                                aPd.put("PROPORTION", aJo.get("PROPORTION"));
                                contractService.saveAnthProportion(aPd);
                            }
                        }
                    }*/
                    contractService.saveProperty(pd);
                }
            }
//            保存账单信息
            if (BILL.size() > 0) {
                for (int i = 0; i < BILL.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BILL.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("IS_DEL", 0); //是否删除
                    pd.put("SORT", jo.get("SORT")); //排序
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建人ID
                    pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("TENANT_ID", tenantId);
                    pd.put("START_DATE", jo.get("START_DATE"));
                    pd.put("END_DATE", jo.get("END_DATE"));
                    pd.put("PAY_DATE", jo.get("PAY_DATE"));
                    pd.put("TOTAL_PRICE", jo.get("TOTAL_PRICE"));
                    pd.put("BILL_TYPE", jo.get("BILL_TYPE"));
                    pd.put("BILL_NAME", jo.get("BILL_NAME"));
                    pd.put("STATE", jo.get("STATE"));
                    pd.put("ACT_PAY_DATE", jo.get("ACT_PAY_DATE"));
                    pd.put("INFO", jo.get("INFO"));
                    pd.put("PROPERTY_ID", jo.get("PROPERTY_ID"));
                    pd.put("PAY_TYPE", "");
                    pd.put("PAY_TYPE_PROPORTION", "");
                    pd.put("PAY_TYPE_MONEY", "");
                    pd.put("MAKE_BILL_TYPE", jo.get("MAKE_BILL_TYPE"));
                    pd.put("ALLOT_BILL", jo.get("ALLOT_BILL"));
                    pd.put("LATE_FEE", jo.get("LATE_FEE"));
                    //变更物业合同 增加BILL_TYPE=2
                    if (pd.get("BILL_TYPE").toString().equals("0") || pd.get("BILL_TYPE").toString().equals("1")||pd.get("BILL_TYPE").toString().equals("2")) {
                        contractService.saveBill(pd);
                    }
                }
            }
            // 保存代收信息
            if (COLLECTION != null && !COLLECTION.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", this.get32UUID());    //主键
                pd.put("CONTRACT_ID", contractId);    //合同ID
                pd.put("TX_TEL", COLLECTION.get("TX_TEL"));
                pd.put("TX_EMAIL", COLLECTION.get("TX_EMAIL"));
                pd.put("BANK_CODE", COLLECTION.get("BANK_CODE"));
                pd.put("ACCOUNT_TYPE", COLLECTION.get("ACCOUNT_TYPE"));
                pd.put("ACCOUNT_NO", COLLECTION.get("ACCOUNT_NO"));
                pd.put("ACCOUNT_NAME", COLLECTION.get("ACCOUNT_NAME"));
                pd.put("PROVINCE", COLLECTION.get("PROVINCE"));
                pd.put("CITY", COLLECTION.get("CITY"));
                pd.put("BANK_NAME", COLLECTION.get("BANK_NAME"));
                pd.put("ACCOUNT_PROP", COLLECTION.get("ACCOUNT_PROP"));
                pd.put("CURRENCYinfo", COLLECTION.get("CURRENCY"));
                pd.put("ID_TYPE", COLLECTION.get("ID_TYPE"));
                pd.put("ID_CARD", COLLECTION.get("ID"));
                pd.put("TEL", COLLECTION.get("TEL"));
                pd.put("ABSTRACT", COLLECTION.get("ABSTRACT"));
                contractService.saveCollection(pd);
            }
/*//            保存提醒信息
            if (REMINDS.size() > 0) {
                for (int i = 0; i < REMINDS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) REMINDS.get(i);
//                    pd.put("MESSAGE_ID", this.get32UUID());    //主键
//                    pd.put("IS_DELETED", 0); //是否删除
                    pd.put("CREATE_USERID", user.getUSER_ID()); //创建人ID
//                    pd.put("CREATE_TIME", new DateUtil().getTime()); //创建时间
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("BILL_ID", "");
                    pd.put("TITLE", jo.get("TYPE") + "收取提醒!");
                    pd.put("CONTENT", jo.get("TYPE") + "收取提醒!");
                    pd.put("TYPE", 3);
//                    pd.put("IS_READ", 0);
                    pd.put("RECEIVER_USERID", "");
                    pd.put("REMIND_TIME", jo.get("PAY_DATE"));

                    sysMessageService.saveMessage(pd);
                }
            }*/

            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "变更合同，提交审核");//提交合同
            oppd.put("CONTRACT_ID", contractId);
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);


            //--------------------个推消息---------------------
            //个推消息
            PageData CID = new PageData();
            String title = "你有一条待审批的合同";
            String text = "请前去审批";
            List<String> list = new ArrayList<String>();
            List<PageData> listcid = contractService.findlistCID(CID);
            for(int i =0 ;i<listcid.size();i++){
                list.add(listcid.get(i).get("CID").toString());
            }
            JSONObject json =new JSONObject();
            json.put("ID",contractId);
            json.put("TYPE",0);
            json.put("TITLE","你有一条待审批的合同");
            json.put("TEXT","请前去审批");
            String ID = json.toString();
            PushToApp.PushPrivate(title,text,list,ID);
            //--------------------个推消息---------------------


            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            logger.error(e.toString(), e);
            PageData pd = new PageData();
            pd.put("id", contractId);
            try {
                contractService.delContract(pd);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 合同退租
     */
    @RequestMapping(value = "/tuizu")
    @ResponseBody
    public PageData tuizu() {
        logBefore(logger, "合同退租");
        PageData res = new PageData();
        PageData data = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            Map map1 = JSONHelper.json2Map(data.toString());
            Map map2 = JSONHelper.json2Map(map1.get("DATA").toString());
            JSONObject RENT = (JSONObject) map2.get("RENT");
            JSONArray BILLS = (JSONArray) map2.get("BILLS");
            JSONObject MONEY = (JSONObject) map2.get("MONEY");

            String contractId = (String) RENT.get("CONTRACT_ID");
            String tenantId = (String) RENT.get("TENANT_ID");
            // 保存退租信息
            if (RENT != null && !RENT.equals("")) {
                PageData pd = new PageData();
                pd.put("CONTRACT_ID", RENT.get("CONTRACT_ID"));
                pd.put("CHECK_STATE", 5);
//                pd.put("STATE", "2d18b637cacf44cc8cb2ead91e496036");
                pd.put("THROW_LEASE_TYPE", RENT.get("THROW_LEASE_TYPE"));
                pd.put("THROW_LEASE_DATE", RENT.get("THROW_LEASE_DATE"));
                pd.put("THROW_LEASE_REASON", RENT.get("THROW_LEASE_REASON"));
                pd.put("THROW_LEASE_INFO", RENT.get("THROW_LEASE_INFO"));
                pd.put("IS_READ", "1");
                pd.put("UPDATE_DATE", new DateUtil().getTime());
                pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
                contractService.editContract(pd);
            }
//            保存退款信息
            if (BILLS.size() > 0) {
                for (int i = 0; i < BILLS.size(); i++) {
                    PageData pd = new PageData();
                    JSONObject jo = (JSONObject) BILLS.get(i);
                    pd.put("ID", this.get32UUID());    //主键
                    pd.put("CONTRACT_ID", contractId);
                    pd.put("TYPE", jo.get("TYPE"));
                    pd.put("MONEY", jo.get("MONEY"));
                    pd.put("INFO", jo.get("INFO"));
                    pd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                    pd.put("CREATE_TIME", new DateUtil().getTime()); //创建时间
                    contractService.saveThrowLease(pd);
                }
            }
//            保存退租待结清账单信息
            if (MONEY != null && !MONEY.equals("")) {
                PageData pd = new PageData();
                pd.put("ID", this.get32UUID());    //主键
                pd.put("IS_DEL", 0); //是否删除
                pd.put("SORT", 0); //排序
                pd.put("CREATE_ID", user.getUSER_ID()); //创建人ID
                pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                pd.put("CONTRACT_ID", contractId);
                pd.put("TENANT_ID", tenantId);
                pd.put("START_DATE", new DateUtil().getDay());
                pd.put("END_DATE", "-");
                pd.put("PAY_DATE", new DateUtil().getDay());
                pd.put("TOTAL_PRICE", MONEY.get("TOTAL_PRICE"));
                pd.put("BILL_TYPE", 3);
                pd.put("BILL_NAME", "退租");
                pd.put("STATE", "682177ade393478e8224f9a3aa385a6c");
                pd.put("ACT_PAY_DATE", "");
                pd.put("INFO", "");
                pd.put("PROPERTY_ID", "");
                pd.put("PAY_TYPE", "");
                pd.put("PAY_TYPE_PROPORTION", "");
                pd.put("PAY_TYPE_MONEY", "");
                pd.put("MAKE_BILL_TYPE", 0);
                pd.put("ALLOT_BILL", 0);
                contractService.saveBill(pd);
            }

            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "合同退租，提交审核");//提交合同
            oppd.put("CONTRACT_ID", contractId);
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);



            //--------------------个推消息---------------------

            //个推消息
            PageData CID = new PageData();
            String title = "你有一条退租的合同信息";
            String text = "请前去审批 ";
            List<PageData> listcid = contractService.findlistCID(CID);
            List<String> cid= PushToApp.userCID("SPQX_HTSP",listcid);//获取由此权限的用户cid(帐单审批权限)
            if(cid.size()>0){
                JSONObject json =new JSONObject();
                json.put("ID",contractId);
                json.put("TYPE",0);
                json.put("TITLE","你有一条退租的合同信息");
                json.put("TEXT","请前去审批");
                String ID = json.toString();
                PushToApp.PushPrivate(title,text,cid,ID);
            }
            //--------------------个推消息---------------------



            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 合同作废
     */
    @RequestMapping(value = "/zuofei")
    @ResponseBody
    public PageData zuofei() {
        logBefore(logger, "合同作废");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {

            String contractId = pd.getString("CONTRACT_ID");
            pd.put("CHECK_STATE", "9");
            pd.put("STATE", "2d18b637cacf44cc8cb2ead91e496036");
            pd.put("IS_READ", "1");
            pd.put("UPDATE_DATE", new DateUtil().getTime());
            pd.put("UPDATE_ID", user.getUSER_ID()); //创建用户
            contractService.editContract(pd);//作废合同
            pd.put("id",contractId);
            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "合同作废，提交审核");//提交合同
            oppd.put("CONTRACT_ID", contractId);
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);



            //--------------------个推消息---------------------

            //个推消息
            PageData CID = new PageData();
            String title = "你有一条作废的合同信息";
            String text = "请前去审批 ";
            List<String> list = new ArrayList<String>();
            List<PageData> listcid = contractService.findlistCID(CID);
            for(int i =0 ;i<listcid.size();i++){
                list.add(listcid.get(i).get("CID").toString());
            }
            JSONObject json =new JSONObject();
            json.put("ID", contractId);
            json.put("TYPE",0);
            json.put("TITLE","你有一条作废的合同信息");
            json.put("TEXT","请前去审批");
            String ID = json.toString();
            PushToApp.PushPrivate(title,text,list,ID);

            //--------------------个推消息---------------------



            res.put("data", "");
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**
     * 根据合同ID获取合同退租原因信息
     */
    @RequestMapping(value = "/findThrowLeaseReasonByIDs")
    @ResponseBody
    public PageData findThrowLeaseReasonByIDs() {
        logBefore(logger, "根据合同ID获取合同退租原因信息");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {

            String DATA_IDS = pd.getString("ID");
            if (null != DATA_IDS && !"".equals(DATA_IDS)) {
                String ArrayDATA_IDS[] = DATA_IDS.split(",");
                List<PageData> data = contractService.findThrowLeaseReasonByIDs(ArrayDATA_IDS);
                res.put("data", data);
            }

            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }


    /********************************************app审批**********************************************/
    /**
     * 获取合同列表
     *
     * @return
     */
    @RequestMapping(value = "/findcontractforcheck",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object findContractForCheck(Page page) {
        logBefore(logger, "获取审批事项合同账单列表");
        PageData pd = new PageData();
        PageData pds = new PageData();
        PageData resultPd = new PageData();
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pds.put("startTime",pd.get("startTime"));
            pds.put("endTime",pd.get("endTime"));
            pds.put("page",pd.get("page"));
            pds.put("limit",pd.get("row"));
            pds.put("USER_ID", user.getUSER_ID());
            PageData data= new PageData();
            List<PageData> list;
            List<PageData> bill_list;
            int num=0;
            // 数据权限开始
            if(null!=pd.get("userid")){
                pd.put("USER_ID",pd.get("userid"));
                PageData puser=userService.findByUserId(pd);
                if ("95bb91515192430bb7a6b5d0a0876542".equals(puser.get("USER_TYPE"))) {
                    getPData(page, pds);
                /*    list = contractService.findContractForCheck(page);//合同 待审核
                    num = GetDatalayui.getPageTotal(num, page.getTotalResult(),page);
                    bill_list = contractService.findContractForCheckBill(page);//账单 待审核
                    num = GetDatalayui.getPageTotal(num, page.getTotalResult(),page);
*/
                    list= contractService.datalistPageConAndPayAndMessageForCheck(page);
                }else {
                    //暂时注释 因为无法获取移动端传来的用户信息 2018年1月9日 17:07:29
                    PageData dataAuthPd = new PageData();
                    dataAuthPd.put("USER_ID", pd.get("userid"));
                    List<PageData> datas = roleService.dataAuthListByUserId(dataAuthPd);
                    String s = "";
                    if (datas != null && datas.size() > 0) {
                        for (int i = 0; i < datas.size(); i++) {
                            s += datas.get(i).getString("DATA_ID") + ",";
                        }
                    }
                    pds.put("USER_ID", pd.get("userid"));
                    pds.put("DATA_IDS", s);
                    getPData(page, pds);
                    list = contractService.findContractForCheck(page);//合同 待审核
                    num = GetDatalayui.getPageTotal(num, page.getTotalResult(),page);
                    bill_list = contractService.findContractForCheckBill(page);//账单 待审核
                    num = GetDatalayui.getPageTotal(num, page.getTotalResult(),page);
                    list.addAll(bill_list);
                }
            } else {
                getPData(page, pds);

              /*  list = contractService.findContractForCheck(page);//合同 待审核
                num = GetDatalayui.getPageTotal(num, page.getTotalResult(),page);
                bill_list = contractService.findContractForCheckBill(page);//账单 待审核
                num = GetDatalayui.getPageTotal(num, page.getTotalResult(),page);*/
                list= contractService.datalistPageConAndPayAndMessageForCheck(page);


            }
          //  list.addAll(bill_list);
           /* resultPd.put("data", list);
            //resultPd.put("dataNUM", list.size());
            resultPd.put("errcode", "00");
            resultPd.put("errmsg", "获取成功");*/
            //判断参数
            resultPd= errorutils.getResults(list,pd);
            datalayui = getLData(page, list);
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return datalayui;
    }


    /**
     * 获取合同详情
     *
     * @return
     */
    @RequestMapping(value = "/findcontractbycontractid")
    @ResponseBody
    public Object findContractByContractId() {
        logBefore(logger, "获取合同详情");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        try {
            pd = this.getPageData();
            PageData contract = new PageData();
            contract = contractService.findContractByContractId(pd);
            List<PageData> rooms = contractService.findRoomByContractId(pd);
            contract.put("rooms", rooms);
            resultPd.put("data", contract);
            resultPd.put("errcode", "0");
            resultPd.put("errmsg", "获取成功");
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }

    /**
     * app审核
     *
     * @return
     */
    @RequestMapping(value = "/checkcontract")
    @ResponseBody
    public Object checkContract() {
        logBefore(logger, "审核合同");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();


            List<PageData> billlist = contractService.findBillByContractId(pd);
            PageData oppd = new PageData();
            if ("1".equals(pd.getString("checkState").toString())) {
                //合同审核通过 关联 修改账单状态
                contractService.check(pd);
                //新建待审核  修改所有合同下的账单状态
                pd.put("CHECK_STATE","1");
                contractService.checkbill(pd);
                if (null != pd.get("info")) {
                    oppd.put("DETAILS", "审核通过:" + pd.get("info").toString());
                }
            } else if ("2".equals(pd.getString("checkState").toString())) {
                // 合同不通过  驳回的时候的账单 怎么办
                contractService.check(pd);
                //不通过  修改所有合同下的账单状态
                for (int i = 0; i < billlist.size(); i++) {
                    contractService.checkbillbohui(billlist.get(i));
                }
                if (null != pd.get("info")) {
                    oppd.put("DETAILS", "审核不通过:" + pd.get("info").toString());
                }
            }
            //保存操作记录
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("CONTRACT_ID", pd.get("id").toString());
            oppd.put("OPERATOR", user.getNAME());//审核人
            recordService.save(oppd);
            resultPd.put("errcode", "0");
            resultPd.put("errmsg", "操作成功");
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }
    /**
     * pc审核
     *
     * @return
     */
    @RequestMapping(value = "/checkcontractPC")
    @ResponseBody
    public Object checkContractPC() {
        logBefore(logger, "审核合同");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();

            //合同审核通过 关联 修改账单状态
            List<PageData> billlist = contractService.findBillByContractId(pd);
            PageData oppd = new PageData();
            pd.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
            pd.put("UPDATE_ID", user.getUSER_ID());//合同变更者
            if ("1".equals(pd.getString("checkState").toString())) {
                //新建待审核  修改所有合同下的账单状态
                if ("新建待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    //最高审核通过后 才把账单状态改成 1
                    PageData contractId = new PageData();
                    contractId.put("id",pd.get("id"));
                    PageData contractList =contractService.findById(contractId);//合同数据
                    int i=Integer.parseInt(contractList.get("CHECK_STATE").toString())+1;
                    pd.put("USER_ID", user.getUSER_ID());
                    PageData data = roleService.shenHeAuth(pd);
                    if(data.containsKey("CONTRACT_AUTH")){
                        if(1==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启一级审核
                            pd.put("checkState","1");
                            PageData billdata = new PageData();
                            billdata.put("id",pd.get("id"));
                            billdata.put("CHECK_STATE","1");
                            contractService.checkbill(billdata);//保存账单状态
                            contractService.check(pd);//审核合同
                            PageData cb = new PageData();
                            cb.put("ID",UuidUtil.get32UUID());
                            cb.put("CREATE_ID",user.getUSER_ID());
                            cb.put("CREATE_DATE",DateUtil.getTimes());
                            cb.put("IS_DEL","0");
                            cb.put("CB_ID",pd.get("id"));
                            cb.put("STATE","1");//1 通过   2 未通过
                            cb.put("REMARK","");//备注
                        }
                        if(2==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启2级审核
                                if(i==3){
                                    pd.put("checkState","1");
                                    PageData billdata = new PageData();
                                    billdata.put("id",pd.get("id"));
                                    billdata.put("CHECK_STATE","1");
                                    contractService.checkbill(billdata);//保存账单状态
                                }else {
                                    String stateStr="0"+i;
                                    pd.put("checkState",stateStr);
                                }
                                //todo 有审核权限等级 的人 直接可以审核通过
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","");//备注
                                contractService.savetbcheck(cb);//保存业务记录

                        }
                        if(3==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启3级审核
                                if(i==4){
                                    pd.put("checkState","1");
                                    PageData billdata = new PageData();
                                    billdata.put("id",pd.get("id"));
                                    billdata.put("CHECK_STATE","1");
                                    contractService.checkbill(billdata);//保存账单状态
                                } else {
                                    String stateStr="0"+i;
                                    pd.put("checkState",stateStr);
                                }
                                //todo 有审核权限等级 的人 直接可以审核通过
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","");//备注
                                contractService.savetbcheck(cb);//保存业务记录

                        }
                        if(4==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启4级审核
                            if(5==i){
                                pd.put("checkState","1");
                                PageData billdata = new PageData();
                                billdata.put("id",pd.get("id"));
                                billdata.put("CHECK_STATE","1");
                                contractService.checkbill(billdata);//保存账单状态
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","");//备注
                            }else {
                                //todo 有审核权限等级 的人 直接可以审核通过
                                String stateStr="0"+i;
                                pd.put("checkState",stateStr);
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }
                        }
                    }
                }
                //退租待审核  删除合同下的所有账单 审核退租账单
                if ("退租待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    PageData contractId = new PageData();
                    contractId.put("id",pd.get("id"));
                    PageData contractList =contractService.findById(contractId);//合同数据
                    int i=0;
                    if("5".equals(contractList.get("CHECK_STATE").toString())){
                        i=Integer.parseInt(contractList.get("CHECK_STATE").toString()+"01")+1;//获取当前的状态为9 补成900然后+1
                    }else {
                        i=Integer.parseInt(contractList.get("CHECK_STATE").toString())+1;//
                    }
                    pd.put("USER_ID", user.getUSER_ID());
                    PageData data = roleService.shenHeAuth(pd);
                    if(data.containsKey("CONTRACT_AUTH")){
                        if(1==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启一级审核
                            tuizu_pass(pd, billlist);
                            PageData cb = new PageData();
                            cb.put("ID",UuidUtil.get32UUID());
                            cb.put("CREATE_ID",user.getUSER_ID());
                            cb.put("CREATE_DATE",DateUtil.getTimes());
                            cb.put("IS_DEL","0");
                            cb.put("CB_ID",pd.get("id"));
                            cb.put("STATE","1");//1 通过   2 未通过
                            cb.put("REMARK","退租审核");//备注
                        }
                        if(2==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启2级审核
                            if(i==503){
                                tuizu_pass(pd, billlist);
                            }else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                //todo 有审核权限等级 的人 直接可以审核通过
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","退租审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }
                        }
                        if(3==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启3级审核
                            if(i==504){
                                tuizu_pass(pd, billlist);
                            } else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                //todo 有审核权限等级 的人 直接可以审核通过
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","退租审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }

                        }
                        if(4==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启4级审核
                            if(505==i){
                                tuizu_pass(pd, billlist);
                            }else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","退租审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }
                        }
                    }

                }
                if ("变更待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    //FIXME 通过新合同 查询出旧合同的id  进行删除  变更通过后的账单怎么办 是在这里处理 还是 在查询的时候处理账单 **已修正
                    //fixme 变更多次的合同  变更之前的合同账单部分可用 变更后的账单 加上之前的账单 假如多次变更 每次变更都有账单的处理问题**已修正
                    PageData contractId = new PageData();
                    contractId.put("id",pd.get("id"));
                    PageData contractList =contractService.findById(contractId);//合同数据
                    int i=0;
                    if("12".equals(contractList.get("CHECK_STATE").toString())){
                        i=Integer.parseInt(contractList.get("CHECK_STATE").toString()+"01")+1;//获取当前的状态为9 补成900然后+1
                    }else {
                        i=Integer.parseInt(contractList.get("CHECK_STATE").toString())+1;//
                    }
                    pd.put("USER_ID", user.getUSER_ID());
                    PageData data = roleService.shenHeAuth(pd);
                    if(data.containsKey("CONTRACT_AUTH")){
                        if(1==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启一级审核
                            change_pass(pd);
                            PageData cb = new PageData();
                            cb.put("ID",UuidUtil.get32UUID());
                            cb.put("CREATE_ID",user.getUSER_ID());
                            cb.put("CREATE_DATE",DateUtil.getTimes());
                            cb.put("IS_DEL","0");
                            cb.put("CB_ID",pd.get("id"));
                            cb.put("STATE","1");//1 通过   2 未通过
                            cb.put("REMARK","变更审核");//备注
                        }
                        if(2==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启2级审核
                            if(i==1203){
                                System.out.println(1);
                                change_pass(pd);
                            }else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                //todo 有审核权限等级 的人 直接可以审核通过
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","变更审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }
                        }
                        if(3==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启3级审核
                            if(i==1204){
                                System.out.println(11);
                                change_pass(pd);
                            } else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                //todo 有审核权限等级 的人 直接可以审核通过
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","变更审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }

                        }
                        if(4==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启4级审核
                            if(1205==i){
                                //todo 有审核权限等级 的人 直接可以审核通过
//                                change_pass(pd);
                            }else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","变更审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }
                        }
                    }
                }
                if ("作废待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    //作废后   删除所有合同下的账单  把合同修改成已完结
                    PageData contractId = new PageData();
                    contractId.put("id",pd.get("id"));
                    PageData contractList =contractService.findById(contractId);//合同数据
                    int i=0;
                    if("9".equals(contractList.get("CHECK_STATE").toString())){
                        i=Integer.parseInt(contractList.get("CHECK_STATE").toString()+"01")+1;//获取当前的状态为9 补成900然后+1
                    }else {
                        i=Integer.parseInt(contractList.get("CHECK_STATE").toString())+1;//
                    }
                    pd.put("USER_ID", user.getUSER_ID());
                    PageData data = roleService.shenHeAuth(pd);
                    if(data.containsKey("CONTRACT_AUTH")){
                        if(1==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启一级审核
                            pd.put("checkState","10");
                            contractService.check(pd);//审核合同
                            PageData contractIds = new PageData();
                            contractId.put("id",pd.get("id"));
                            List<PageData> billlists = contractService.findBillByContractId(contractIds);//根据合同id 查找合同下的账单
                            if(billlists.size()>0){
                                contractService.DELbill(billlists);
                            }
                            contractService.InvalidContract(contractId);
                            PageData cb = new PageData();
                            cb.put("ID",UuidUtil.get32UUID());
                            cb.put("CREATE_ID",user.getUSER_ID());
                            cb.put("CREATE_DATE",DateUtil.getTimes());
                            cb.put("IS_DEL","0");
                            cb.put("CB_ID",pd.get("id"));
                            cb.put("STATE","1");//1 通过   2 未通过
                            cb.put("REMARK","");//备注
                        }
                        if(2==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启2级审核
                            if(i==903){
                                pd.put("checkState",10);//退租待结清
                                contractService.check(pd);//审核合同
                                PageData contractIds = new PageData();
                                contractId.put("id",pd.get("id"));
                                List<PageData> billlists = contractService.findBillByContractId(contractIds);//根据合同id 查找合同下的账单
                                if(billlists.size()>0){
                                    contractService.DELbill(billlists);
                                }
                                contractService.InvalidContract(contractId);
                            }else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                            }
                            //todo 有审核权限等级 的人 直接可以审核通过
                            contractService.check(pd);//审核合同
                            PageData cb = new PageData();
                            cb.put("ID",UuidUtil.get32UUID());
                            cb.put("CREATE_ID",user.getUSER_ID());
                            cb.put("CREATE_DATE",DateUtil.getTimes());
                            cb.put("IS_DEL","0");
                            cb.put("CB_ID",pd.get("id"));
                            cb.put("STATE","1");//1 通过   2 未通过
                            cb.put("REMARK","");//备注
                            contractService.savetbcheck(cb);//保存业务记录

                        }
                        if(3==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启3级审核
                            if(i==904){
                                pd.put("checkState",10);//退租待结清
                                contractService.check(pd);//审核合同
                                PageData contractIds = new PageData();
                                contractId.put("id",pd.get("id"));
                                List<PageData> billlists = contractService.findBillByContractId(contractIds);//根据合同id 查找合同下的账单
                                if(billlists.size()>0){
                                    contractService.DELbill(billlists);
                                }
                                contractService.InvalidContract(contractId);
                            } else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                            }
                            //todo 有审核权限等级 的人 直接可以审核通过
                            contractService.check(pd);//审核合同
                            PageData cb = new PageData();
                            cb.put("ID",UuidUtil.get32UUID());
                            cb.put("CREATE_ID",user.getUSER_ID());
                            cb.put("CREATE_DATE",DateUtil.getTimes());
                            cb.put("IS_DEL","0");
                            cb.put("CB_ID",pd.get("id"));
                            cb.put("STATE","1");//1 通过   2 未通过
                            cb.put("REMARK","");//备注
                            contractService.savetbcheck(cb);//保存业务记录

                        }
                        if(4==Integer.parseInt(data.get("CONTRACT_AUTH").toString())){//开启4级审核
                            if(905==i){
                                //todo 有审核权限等级 的人 直接可以审核通过
                                pd.put("checkState",10);//退租待结清
                                contractService.check(pd);//审核合同
                                PageData contractIds = new PageData();
                                contractId.put("id",pd.get("id"));
                                List<PageData> billlists = contractService.findBillByContractId(contractIds);//根据合同id 查找合同下的账单
                                if(billlists.size()>0){
                                    contractService.DELbill(billlists);
                                }
                                contractService.InvalidContract(contractId);
                            }else {
                                String stateStr=""+i;
                                pd.put("checkState",stateStr);
                                contractService.check(pd);//审核合同
                                PageData cb = new PageData();
                                cb.put("ID",UuidUtil.get32UUID());
                                cb.put("CREATE_ID",user.getUSER_ID());
                                cb.put("CREATE_DATE",DateUtil.getTimes());
                                cb.put("IS_DEL","0");
                                cb.put("CB_ID",pd.get("id"));
                                cb.put("STATE","1");//1 通过   2 未通过
                                cb.put("REMARK","作废审核");//备注
                                contractService.savetbcheck(cb);//保存业务记录
                            }
                        }
                    }


                }
                if (null != pd.get("DETAILS")) {
                    oppd.put("DETAILS", "审核通过:" + pd.get("DETAILS").toString());
                }
            } else if ("2".equals(pd.getString("checkState").toString())) {
                // 合同不通过  驳回的时候的账单 怎么办
                if ("新建待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    contractService.check(pd);
                }
                //变更待审核不通过
                if ("变更待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    //变更不通过的 合同 1删除当前的合同 2把历史合同的状态 改为 变更不通过
                    PageData newcontractId = new PageData();
                    newcontractId.put("id",pd.get("id"));
//                    contractService.delContract(newcontractId);
                    PageData newcontractList =contractService.findById(newcontractId);
                    PageData oldcontractList = new PageData();
                    oldcontractList.put("id",newcontractList.get("BEFORE_CHANGE_CONTRACT_ID"));
                    oldcontractList.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
                    oldcontractList.put("UPDATE_ID", user.getUSER_ID());//合同变更者
                    oldcontractList.put("checkState",1);//变更不通过 把变更前的合同 还原状态
                    contractService.check(oldcontractList);
                    //变更不通过 把新合同状态改为 变更不通过
                    PageData newcontract = new PageData();
                    newcontract.put("id",pd.get("id"));
                    newcontract.put("UPDATE_DATE", new DateUtil().getTime());//合同的更新时间
                    newcontract.put("UPDATE_ID", user.getUSER_ID());//合同变更者
                    newcontract.put("checkState",13);//变更不通过 把变更前的合同 还原状态
                    contractService.check(newcontract);
                    //fixme 合同变更不通过的时候 删除合同关联的信息 如：新租户信息 为了查看变更记录 不做删除
                    PageData TenantEntity = new PageData();
                    TenantEntity.put("IS_DEL","1");
                    TenantEntity.put("ID",newcontractList.get("PERSON_ID"));
//                    customerService.delete(TenantEntity);
                    //fixme 删除其他合同关联信息 物理删除？
                    PageData delOther = new PageData();
                    delOther.put("ID",pd.get("id"));
//                    contractService.delOtherContract(delOther);
                    //保存操作记录
                    oppd.put("ID", this.get32UUID());    //主键
                    oppd.put("IS_DEL", 0); //是否删除
                    oppd.put("SORT", 0); //排序
                    oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
                    oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
                    oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
                    oppd.put("DETAILS", "审核不通过:" + pd.get("DETAILS").toString());
                    oppd.put("CONTRACT_ID", newcontractList.get("BEFORE_CHANGE_CONTRACT_ID"));
                    oppd.put("OPERATOR", user.getNAME());//审核人
                    recordService.save(oppd);

                }
                if ("退租待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    pd.put("checkState",8);//退租不通过   账单不用修改 把合同 改不通过
                    contractService.check(pd);
                }
                if ("作废待审核".equals(pd.getString("CHECK_STATE").toString())) {
                    //作废不通过 状态还原就行
                    pd.put("checkState",11);//退租待结清
                    contractService.check(pd);
                }
                if (null != pd.get("DETAILS")) {
                    oppd.put("DETAILS", "审核不通过:" + pd.get("DETAILS").toString());
                }
            }
            //保存操作记录
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("CONTRACT_ID", pd.get("id").toString());
            oppd.put("OPERATOR", user.getNAME());//审核人
            recordService.save(oppd);
            resultPd.put("errcode", "0");
            resultPd.put("errmsg", "操作成功");
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }
    //退租审核通过
    private void tuizu_pass(PageData pd, List<PageData> billlist) throws Exception {
        pd.put("checkState",14);//退租待结清
        contractService.check(pd);
        if (billlist.size() > 0) {
            for (int i = 0; i < billlist.size(); i++) {
                if (!"退租".equals(billlist.get(i).get("BILL_NAME"))) {
                    //删除其他账单信息
//                                System.out.println(billlist.get(i).get("BILL_NAME"));
                    PageData delldata= billlist.get(i);
                    contractService.checkbillDEL(delldata);
                }
                if ("退租".equals(billlist.get(i).get("BILL_NAME"))) {
                    //修改当前退租账单
                    contractService.checkbilltz(billlist.get(i));
                }
            }
        }
    }

    //变更待审核通过
    private void change_pass(PageData pd) throws Exception {
        pd.put("checkState",1);
        contractService.check(pd);
        PageData contractId = new PageData();
        contractId.put("id",pd.get("id"));
        PageData contractList =contractService.findById(contractId);//新合同数据
        contractId.put("id",contractList.get("BEFORE_CHANGE_CONTRACT_ID"));
        contractService.delContract(contractId);//删除老合同
        //变更审核通过后 需要作废的账单作废
        if(contractList.size()>0){
            String str = contractList.get("DEL_BILL_IDS").toString();
            List<String> result = Arrays.asList(str.split(","));
            for(int i=0;i<result.size();i++){
                PageData del_bill = new PageData();
                del_bill.put("ID",result.get(i));
                contractService.ObsoleteBills(del_bill);
            }
        }
        //变更审核通过后 的 新合同账单 直接修改状态 check_state 为1  通过
        contractId.put("CHECK_STATE","1");
        contractService.checkbill(contractId);
        //把新账单的状态 正常
        PageData billdata = new PageData();
        billdata.put("id",pd.get("id"));
        billdata.put("CHECK_STATE","1");
        contractService.checkbill(billdata);//保存账单状态
        //把有用的旧账单（老合同的所有账单）的账单的合同id 修改为 新合同ID 新的合同账单不用处理
        PageData up_contractId = new PageData();
        up_contractId.put("CONTRACT_ID",pd.get("id"));
        up_contractId.put("OLD_CONTRACT_ID",contractList.get("BEFORE_CHANGE_CONTRACT_ID"));
        contractService.ChangeOfContractPassed(up_contractId);
    }

    /**
     * 消息中心列表
     *
     * @return
     */
    @RequestMapping(value = "/messagelist",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object messagelist(Page page) {
        PageData pd = new PageData();
        PageData pds = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        PageData resultPd = new PageData();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pds.put("page",pd.get("page"));
            pd.put("USER_ID", pd.get("id"));
            PageData dataAuth = roleService.authListByLoginUser(pd);
            pds.put("limit",pd.get("row"));
            if(null != pd.get("id") && !"".equals(pd.get("id"))){
                pds.put("id",pd.get("id"));
            }
            if(null != pd.get("type") && !"".equals(pd.get("type"))){
                pds.put("type",pd.get("type"));
            }
            if(null != pd.get("state") && !"".equals(pd.get("state"))){
                pds.put("state",pd.get("state"));
            }
            if(null != pd.get("startTime") && !"".equals(pd.get("startTime"))){
                pds.put("startTime",pd.get("startTime"));
            }
            if(null != pd.get("endTime") && !"".equals(pd.get("endTime"))){
                pds.put("endTime",pd.get("endTime"));
            }
            List<PageData> list= new LinkedList<>();
            pds.put("USER_ID",user.getUSER_ID());
            getPData(page, pds);
            PageData puser=userService.findByUserId(pd);
            if ("95bb91515192430bb7a6b5d0a0876542".equals(puser.get("USER_TYPE"))) {
              /*  list = contractService.findmessagelist(page);//待审核 账单
                List<PageData> listcontract = contractService.findmessagelistcontract(page);//待审核 合同
                List<PageData> listPay = contractService.findmessagelistPay(page);//已支付的 账单
                list.addAll(listPay);
                list.addAll(listcontract);*/
                //根据  待审核  账单，待审核合同， 已支付账单
                list=  contractService.findConAndPayAndMessage(page);

            }else {
                PageData dataAuthPd = new PageData();
                dataAuthPd.put("USER_ID",pd.get("id"));
                List<PageData> datas = roleService.dataAuthListByUserId(dataAuthPd);
                String s = "";
                if (datas != null && datas.size() > 0) {
                    for (int i = 0; i < datas.size(); i++) {
                        s += datas.get(i).getString("DATA_ID") + ",";
                    }
                }
                pds.put("USER_ID",pd.get("id"));
                pds.put("DATA_IDS", s);

               /* pd.put("USER_ID", user.getUSER_ID());
                PageData shenheAuth = roleService.authListByLoginUser(pd);
                if (!"95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                    String dataStr = "(";
                    if (shenheAuth.get("AUTH_CODE").toString().indexOf("SHQX_1") != -1) {
                        //一级权限
                        dataStr += "\"01\",\"9\",\"12\",\"5\",";
                    }
                    if (shenheAuth.get("AUTH_CODE").toString().indexOf("SHQX_2") != -1) {
                        //二级权限
                        dataStr += "\"02\",\"902\",\"1202\",\"502\",";
                    }
                    if (shenheAuth.get("AUTH_CODE").toString().indexOf("SHQX_3") != -1) {
                        //三级权限
                        dataStr += "\"03\",\"903\",\"1203\",\"503\",";
                    }
                    if (shenheAuth.get("AUTH_CODE").toString().indexOf("SHQX_4") != -1) {
                        //四级权限
                        dataStr += "\"04\",\"904\",\"1204\",\"504\",";
                    }
                    dataStr += "\"-1\")";
                    pds.put("CHECK_STATE", dataStr);
                }*/
                getPData(page, pds);
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_ZDSP")!=-1) {
                  //待审核 账单
                    pds.put("SPQX_ZDSP","SPQX_ZDSP");
                }
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_HTSP")!=-1) {
                    pds.put("SPQX_HTSP","SPQX_HTSP");
                }
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_ZDSP")!=-1) {
                   //已支付的 账单
                    pds.put("SPQX_ZDSP","SPQX_ZDSP");
                }




                list=  contractService.findConAndPayAndMessage(page);
                //当 更新时间为null 的时候 list 无数据 修改报空指针问题 2018年3月5日 10:06:26
                if(list.size()>0){
                    SortUtil.sort(list,"CREATE_DATE","desc");//默认创建时间降序
                    SortUtil.sort(list,"IS_READ","desc");//读取降序 未读 排前面 0已读  1未读
                }
            }
           // resultPd.put("dataNUM", list.size());
            //resultPd=errorutils.getResults(list,pd);
            varList = list;
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }




    /**
     * 消息中心列表
     *
     * @return
     */
    /*@RequestMapping(value = "/messagelist")
    @ResponseBody
    public Object messagelist() {
        logBefore(logger, "获取审批事项合同账单列表");
        PageData pd = new PageData();
        PageData resultPd = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            //有审批权限
            pd.put("USER_ID", user.getUSER_ID());
            PageData dataAuth = roleService.authListByLoginUser(pd);
            List<PageData> list= new ArrayList<>();
            // 数据权限开始
            if ("95bb91515192430bb7a6b5d0a0876542".equals(user.getUSER_TYPE())) {
                pd.put("USER_ID", user.getUSER_ID());
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_ZDSP")!=-1) {
                    list = contractService.findmessagelist(pd);//待审核 账单
                }
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_HTSP")!=-1) {
                    List<PageData> listcontract = contractService.findmessagelistcontract(pd);//待审核 合同
                    list.addAll(listcontract);
                }
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_ZDSP")!=-1) {
                    List<PageData> listPay = contractService.findmessagelistPay(pd);//已支付的 账单
                    list.addAll(listPay);
                }
            } else {
                //暂时注释 因为无法获取移动端传来的用户信息 2018年1月9日 17:05:10
               *//* PageData dataAuthPd = new PageData();
                dataAuthPd.put("USER_ID", user.getUSER_ID());
                List<PageData> datas = roleService.dataAuthListByUserId(dataAuthPd);
                String s = "dataAuth";
                if (datas != null && datas.size() > 0) {
                    for (int i = 0; i < datas.size(); i++) {
                        s += datas.get(i).getString("DATA_ID") + ",";
                    }
                }
                pd.put("USER_ID", user.getUSER_ID());
                pd.put("DATA_IDS", s);*//*
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_ZDSP")!=-1) {
                    list = contractService.findmessagelist(pd);//待审核 账单
                }
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_HTSP")!=-1) {
                    List<PageData> listcontract = contractService.findmessagelistcontract(pd);//待审核 合同
                    list.addAll(listcontract);
                }
                if(dataAuth.get("AUTH_CODE").toString().indexOf("SPQX_ZDSP")!=-1) {
                    List<PageData> listPay = contractService.findmessagelistPay(pd);//已支付的 账单
                    list.addAll(listPay);
                }
            }
            SortUtil.sort(list,"CREATE_DATE","desc");//默认创建时间降序
            SortUtil.sort(list,"IS_READ","desc");//读取降序 未读 排前面 0已读  1未读
            resultPd.put("dataNUM", list.size());
            resultPd=errorutils.getResults(list,pd);
        } catch (Exception e) {
            resultPd.put("errcode", "1");
            resultPd.put("errmsg", "内部错误");
            logger.error(e.toString(), e);
        }
        return resultPd;
    }*/




    /**
     * 点击查看 消息中心列表后 更新 消息状态 消息中心列表阅读后 修改消息状态
     */
    @RequestMapping(value = "/editmessagelist")
    @ResponseBody
    public PageData editmessagelist() {
        logBefore(logger, "修改Business");
        PageData res = new PageData();
        PageData pd = this.getPageData();

        try {
            if (null != pd.get("TYPE") && null != pd.get("id")) {
                if ("0".equals(pd.get("TYPE").toString())) {
                    contractService.editmessagelistCONTRACT(pd);
                }
                if ("1".equals(pd.get("TYPE").toString())) {
                    contractService.editmessagelistBILL(pd);
                }
            } else {
                res.put("data", "TYPE类型或者id未定义");
            }
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }





    /**
     * 租客合同app接口
     */
    @RequestMapping(value = "/contract",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object contract(Page page) {
        PageData pd = new PageData();
        PageData pds = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pds.put("page",pd.get("page"));
            pds.put("limit",pd.get("row"));
            if(null != pd.get("state_id")){
                pds.put("state_id",pd.get("state_id"));
                if("93fc53568525558742658f3542856566".equals(pd.get("state_id").toString())){//将到期的逻辑处理
                    pds.put("state_id", null);
                    pds.put("date_flag",DateUtil.getAfterDayDate("90"));
                }
                if("2d18b637cacf44cc8cb2ead91e496036".equals(pd.get("state_id").toString())){//进行中的合同
                    pds.put("ing_flag",DateUtil.getDay());
                }
            }
            if(null != pd.get("time")){
                pds.put("time",pd.get("time"));
            }
            if(null != pd.get("trad_id")){
                pds.put("trad_id",pd.get("trad_id"));
            }
            getPData(page, pds);
            // 数据权限开始
            if (null != pd.get("userid")) {
//                pd.put("USER_ID", pd.get("userid"));
//                PageData puser = userService.findByUserId(pd);
//                if ("95bb91515192430bb7a6b5d0a0876542".equals(puser.get("USER_TYPE"))) {
//                    pd.put("USER_ID", pd.get("userid"));
//                    varList = contractService.contract(page);
//                    datalayui = getLData(page, varList);
//                } else {
                    //暂时注释 因为无法获取移动端传来的用户信息 2018年1月9日 17:08:16
                    PageData dataAuthPd = new PageData();
                    dataAuthPd.put("USER_ID", pd.get("userid"));
                    List<PageData> datas = roleService.dataAuthListByUserId(dataAuthPd);
                    String s = "";
                    if (datas != null && datas.size() > 0) {
                        for (int i = 0; i < datas.size(); i++) {
                            s += datas.get(i).getString("DATA_ID") + ",";
                        }
                    }
                    pds.put("USER_ID", pd.get("userid"));
                    pds.put("DATA_IDS", s);
                    pds.put("COMPANY_ID", user.getCOMPANY_ID());
                    page.setPd(pds);
                    PageData dataAuth = roleService.authListByLoginUser(pd);
                    varList = contractService.contract(page);
                    datalayui = getLData(page, varList);
//                }
            }else {
                varList = contractService.contract(page);
                datalayui = getLData(page, varList);
            }

        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**********************************app贷款合同开始***********************************/

    /**
     * 进行中的贷款合同
     */
    @RequestMapping(value = "/contractloan",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object contractloan(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            pd = this.getPageData();
            pd.put("USER_ID", user.getUSER_ID());
            if(!"".equals(pd.getString("amount"))&&null!=pd.getString("amount")){
                String loan_price=pd.get("amount").toString();
                //分解 贷款数
                String price[] = loan_price.split("-");
                if(price.length>1){
                    String s_price=price[0].replace("w","0000");
                    String e_price=price[1].replace("w","0000");
                    pd.put("s_price",s_price);
                    pd.put("e_price",e_price);
                }else {
                    String e_price=price[0].substring(0, price[0].indexOf("w"));
                    pd.put("s_price",e_price+"0000");
                }
            }
            if (null != pd.get("state")) {

                switch (pd.get("state").toString()){
                    case "1"://已到期
                        pd.put("state", null);
                        pd.put("date_out", DateUtil.getDay());
                        break;
                    case "2"://将到期的逻辑处理
                        pd.put("state", null);
                        pd.put("date_flag", DateUtil.getAfterDayDate("90"));
                        break;
                    case "3"://进行中
                        pd.put("state", null);
                        pd.put("state", "2d18b637cacf44cc8cb2ead91e496036");
                        break;
                    case "4"://已完结
                        pd.put("state", null);
                        pd.put("state", "43ac91b97d144550aed7ea1c01de60ee");
                        break;
                }
            }
            pd.put("limit",pd.get("row"));
            getPData(page, pd);
            varList = loanService.listcontractLoan(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 根据合同ID获取贷款合同详情信息
     */
    @RequestMapping(value = "/loaninfo")
    @ResponseBody
    public PageData loaninfo() {
        logBefore(logger, "根据合同ID获取合同详情信息");
        PageData res = new PageData();
        PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            PageData data = new PageData();
            pd.put("USER_ID", user.getUSER_ID());
            List<PageData> contractData = loanService.find_loan_info(pd);
            List<PageData> billData = contractService.findBillByContractId(pd);
            List<PageData> attachmentData = attachmentService.findByOId(pd);
            if(contractData.size()>0){
                data.put("contract", contractData.get(0));
            }
            data.put("bill", billData);
            data.put("attachment", attachmentData);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }

        return res;
    }

    /**********************************贷款合同结束****************************************************/

}
